<template>
  <div class="user-management animate-in">
    <div class="user-card">
      <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
        <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 120px; margin-right: 8px;">
          <el-option label="全部" :value="''" />
          <el-option label="启用" :value="'enabled'" />
          <el-option label="禁用" :value="'disabled'" />
        </el-select>
        <el-input
          v-model="search"
          placeholder="搜索用户名"
          style="width: 200px;"
          clearable
          @input="onSearch"
        />
        <el-button class="create-user-btn" @click="openCreateDialog">新增用户</el-button>
      </div>
      
      <el-table :data="pagedTableData" row-key="Id" style="width: 100%" v-loading="loading" class="pretty-table">
        <el-table-column label="" align="center" width="80">
          <template #default="scope">
            <img
              :src="scope.row.avatar && scope.row.avatar.url ? scope.row.avatar.url : defaultAvatarUrl"
              :alt="scope.row.Username"
              :style="{ width: '56px', height: '56px', borderRadius: '50%', objectFit: 'cover' }"
              @error="handleAvatarError($event, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="Username" label="用户名" align="left" />
        <el-table-column label="角色" align="center">
          <template #default="scope">
            <div class="role-tags-row">
              <el-tag v-for="role in (scope.row.Roles || [])" :key="role.Id" class="role-tag">
                {{ role.RoleName }}
              </el-tag>
              <span v-if="!scope.row.Roles || scope.row.Roles.length === 0">无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限" align="center">
          <template #default="scope">
            <div class="permission-tags-row">
              <el-tag v-for="perm in (scope.row.Permissions || [])" :key="perm.Id" class="pretty-tag">
                {{ perm.PermissionName }}
              </el-tag>
              <span v-if="!scope.row.Permissions || scope.row.Permissions.length === 0">无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="IsEnabled" label="启用状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.IsEnabled ? 'success' : 'info'">
              {{ scope.row.IsEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="user-actions-row">
              <el-button size="small" @click="openAssignRoleDialog(scope.row)">
                <el-icon><UserFilled /></el-icon>
                分配角色
              </el-button>
              <el-button
                size="small"
                :type="scope.row.IsEnabled ? 'danger' : 'success'"
                @click="toggleUserStatus(scope.row)"
              >
                <el-icon><SwitchButton /></el-icon>
                {{ scope.row.IsEnabled ? '禁用' : '启用' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          :page-size="pageSize"
          :current-page="currentPage"
          :total="tableData.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="createDialogVisible" title="新增用户" width="400px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="80px">
        <el-form-item label="用户名" prop="Username">
          <el-input v-model="createForm.Username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="Password">
          <el-input v-model="createForm.Password" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false" :disabled="createLoading">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="createLoading">
          {{ createLoading ? '创建中...' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="assignRoleDialogVisible" title="分配角色" width="500px">
      <el-form :model="assignRoleForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="assignRoleForm.UserName" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <div v-if="allRoles.length === 0" style="text-align: center; color: #999; padding: 20px;">
            正在加载角色列表...
          </div>
          <div v-else>
            <el-radio-group v-model="assignRoleForm.RoleId">
              <el-radio v-for="role in allRoles" :key="role.Id" :label="role.Id">
                <span class="role-name">{{ role.RoleName }}</span>
              </el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignRole" :loading="assignRoleLoading">
          {{ assignRoleLoading ? '处理中...' : '保存角色' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, SwitchButton } from '@element-plus/icons-vue'
import axios from 'axios'
import { BASE_URL } from '@/api/baseurl.js'
import { getUserAvatarsBatch } from '@/api/user.js'
import { useRoute } from 'vue-router'

const users = ref([])
const allRoles = ref([])
const loading = ref(false)
const createDialogVisible = ref(false)
const assignRoleDialogVisible = ref(false)
const createLoading = ref(false)
const assignRoleLoading = ref(false)
const search = ref('')
const statusFilter = ref('')
const defaultAvatarUrl = '/src/images/01.jpg'

const createForm = reactive({ 
  Username: '', 
  Password: ''
})

const createRules = { 
  Username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  Password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const createFormRef = ref()
const assignRoleForm = reactive({ 
  UserId: '', 
  UserName: '', 
  RoleId: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const API_BASE = BASE_URL + '/api'

// 添加缓存机制
const userCache = ref(new Map())
const roleCache = ref(new Map())
const permissionCache = ref(new Map())

const route = useRoute()

watch(
  () => route.query.refresh,
  () => {
    fetchUsers()
  }
)

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const tableData = computed(() => {
  let data = Array.isArray(users.value) ? users.value.slice() : []
  if (statusFilter.value === 'enabled') {
    data = data.filter(user => user.IsEnabled)
  } else if (statusFilter.value === 'disabled') {
    data = data.filter(user => !user.IsEnabled)
  }
  if (search.value) {
    data = data.filter(user => user.Username?.toLowerCase().includes(search.value.toLowerCase()))
  }
  return data
})

// 分页后的数据
const pagedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 分页处理函数
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

function handleCurrentChange(val) {
  currentPage.value = val
}

function onSearch() {
  currentPage.value = 1
}

// 优化的用户数据获取函数
async function fetchUsers() {
  loading.value = true
  const token = localStorage.getItem('token')
  
  try {
    // 1. 获取用户列表
    const userRes = await axios.get(`${API_BASE}/user/all`, {
      headers: { Authorization: token ? `Bearer ${token}` : '' }
    })
    
    if (!userRes.data?.Data) {
      users.value = []
      return
    }
    
    const userList = userRes.data.Data
    
    // 2. 并发获取所有角色和权限数据（一次性获取，避免重复请求）
    const [rolesRes, permissionsRes] = await Promise.all([
      axios.get(`${API_BASE}/role`, {
        headers: { Authorization: token ? `Bearer ${token}` : '' }
      }),
      axios.get(`${API_BASE}/permission`, {
        headers: { Authorization: token ? `Bearer ${token}` : '' }
      })
    ])
    
    // 缓存角色和权限数据
    const allRoles = rolesRes.data?.Data || []
    const allPermissions = permissionsRes.data?.Data || []
    
    allRoles.forEach(role => roleCache.value.set(role.Id, role))
    allPermissions.forEach(perm => permissionCache.value.set(perm.Id, perm))
    
    // 3. 并发获取所有用户的角色信息
    const userRolesPromises = userList.map(async user => {
      try {
        const roleRes = await axios.get(`${API_BASE}/user/${user.Id}/roles`, {
          headers: { Authorization: token ? `Bearer ${token}` : '' }
        })
        return { userId: user.Id, roles: roleRes.data?.Data || [] }
      } catch {
        return { userId: user.Id, roles: [] }
      }
    })
    
    const userRolesResults = await Promise.all(userRolesPromises)
    
    // 4. 构建用户角色映射
    const userRolesMap = new Map()
    userRolesResults.forEach(result => {
      userRolesMap.set(result.userId, result.roles)
    })
    
    // 5. 并发获取所有角色的权限信息（去重）
    const uniqueRoleIds = [...new Set(userRolesResults.flatMap(r => r.roles.map(role => role.Id)))]
    const rolePermissionsPromises = uniqueRoleIds.map(async roleId => {
      try {
        const permRes = await axios.get(`${API_BASE}/role/${roleId}/permissions`, {
          headers: { Authorization: token ? `Bearer ${token}` : '' }
        })
        return { roleId, permissions: permRes.data?.Data || [] }
      } catch {
        return { roleId, permissions: [] }
      }
    })
    
    const rolePermissionsResults = await Promise.all(rolePermissionsPromises)
    
    // 6. 构建角色权限映射
    const rolePermissionsMap = new Map()
    rolePermissionsResults.forEach(result => {
      rolePermissionsMap.set(result.roleId, result.permissions)
    })
    
    // 7. 组装最终用户数据
    userList.forEach(user => {
      const userRoles = userRolesMap.get(user.Id) || []
      user.Roles = userRoles
      
      // 收集用户所有角色的权限并去重
      const userPermissions = []
      userRoles.forEach(role => {
        const rolePerms = rolePermissionsMap.get(role.Id) || []
        userPermissions.push(...rolePerms)
      })
      
      // 去重权限
      user.Permissions = userPermissions.filter((perm, index, self) => 
        index === self.findIndex(p => p.Id === perm.Id)
      )
    })
    
    // 8. 批量获取头像
    const userIds = userList.map(user => user.Id)
    let avatarList = []
    try {
      const avatarRes = await getUserAvatarsBatch(userIds)
      avatarList = avatarRes.data?.Data || []
    } catch (e) {
      avatarList = []
    }
    const avatarMap = {}
    avatarList.forEach(item => {
      avatarMap[item.userId] = item.avatar
    })
    userList.forEach(user => {
      const avatar = avatarMap[user.Id]
      user.avatar = avatar
        ? {
            ...avatar,
            url: avatar.url ? BASE_URL + avatar.url : null
          }
        : { url: null, hasAvatar: false }
    })
    users.value = userList
    
  } catch (error) {
    console.error('获取用户数据失败:', error)
    ElMessage.error('获取用户数据失败')
    users.value = []
  } finally {
    loading.value = false
  }
}

// 优化的角色获取函数（使用缓存）
async function fetchRoles() {
  // 如果缓存中有数据，直接使用
  if (allRoles.value.length > 0) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    const res = await axios.get(`${API_BASE}/role`, {
      headers: { Authorization: token ? `Bearer ${token}` : '' }
    })
    
    if (res.data?.Data) {
      allRoles.value = res.data.Data
      // 更新缓存
      res.data.Data.forEach(role => roleCache.value.set(role.Id, role))
    } else {
      allRoles.value = []
      ElMessage.warning('未获取到角色列表')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    allRoles.value = []
    ElMessage.error('获取角色列表失败')
  }
}

function openCreateDialog() {
  createForm.Username = ''
  createForm.Password = ''
  createDialogVisible.value = true
}

function handleCreate() {
  createFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    createLoading.value = true
    try {
      const token = localStorage.getItem('token')
      const res = await axios.post(`${API_BASE}/user`, {
        Username: createForm.Username,
        Password: createForm.Password
      }, {
        headers: {
          Authorization: token ? `Bearer ${token}` : ''
        }
      })
      
      if (res.data && res.data.Code === 200) {
        ElMessage.success('用户创建成功')
        createDialogVisible.value = false
        createFormRef.value.resetFields()
        fetchUsers()
      } else {
        ElMessage.error(res.data.Message || '创建失败')
      }
    } catch (error) {
      console.error('创建用户失败:', error)
      if (error.response && error.response.data && error.response.data.Message) {
        ElMessage.error(error.response.data.Message)
      } else {
        ElMessage.error('创建用户失败，请重试')
      }
    } finally {
      createLoading.value = false
    }
  })
}

async function openAssignRoleDialog(row) {
  assignRoleForm.UserId = row.Id
  assignRoleForm.UserName = row.Username
  // 获取用户当前角色（只取第一个）
  const token = localStorage.getItem('token')
  const res = await axios.get(`${API_BASE}/user/${row.Id}/roles`, {
    headers: { Authorization: token ? `Bearer ${token}` : '' }
  })
  if (res.data && res.data.Data && res.data.Data.length > 0) {
    assignRoleForm.RoleId = res.data.Data[0].Id
  } else {
    assignRoleForm.RoleId = ''
  }
  assignRoleDialogVisible.value = true
  await fetchRoles()
}

// 优化的角色分配函数
async function handleAssignRole() {
  assignRoleLoading.value = true
  try {
    const token = localStorage.getItem('token')
    const currentUser = users.value.find(u => u.Id === assignRoleForm.UserId)
    const currentRoleIds = (currentUser?.Roles || []).map(r => r.Id)
    
    // 批量处理角色分配
    const promises = []
    
    // 移除所有现有角色
    for (const roleId of currentRoleIds) {
      promises.push(
        axios.post(`${API_BASE}/user/${assignRoleForm.UserId}/remove-role?roleId=${roleId}`, {}, {
          headers: { Authorization: token ? `Bearer ${token}` : '' }
        })
      )
    }
    
    // 分配新选中的角色
    if (assignRoleForm.RoleId) {
      promises.push(
        axios.post(`${API_BASE}/user/${assignRoleForm.UserId}/assign-role?roleId=${assignRoleForm.RoleId}`, {}, {
          headers: { Authorization: token ? `Bearer ${token}` : '' }
        })
      )
    }
    
    if (promises.length > 0) {
      await Promise.all(promises)
      ElMessage.success('角色分配成功')
    } else {
      ElMessage.info('角色没有变化')
    }
    
    assignRoleDialogVisible.value = false
    // 清除缓存，强制重新获取数据
    userCache.value.clear()
    await fetchUsers()
    
  } catch (error) {
    console.error('角色分配失败:', error)
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message)
    } else {
      ElMessage.error('角色分配失败，请重试')
    }
  } finally {
    assignRoleLoading.value = false
  }
}

// 优化的用户状态切换函数
async function toggleUserStatus(row) {
  try {
    const token = localStorage.getItem('token')
    const url = `${API_BASE}/user/${row.Id}/${row.IsEnabled ? 'disable' : 'enable'}`
    
    const res = await axios.post(url, {}, {
      headers: { Authorization: token ? `Bearer ${token}` : '' }
    })
    
    if (res.data?.Code === 200) {
      ElMessage.success(res.data.Message || (row.IsEnabled ? '禁用成功' : '启用成功'))
      // 只更新当前用户的状态，避免重新获取所有数据
      row.IsEnabled = !row.IsEnabled
    } else if (res.data?.Message) {
      ElMessage.error(res.data.Message)
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('切换用户状态失败:', error)
    if (error.response?.data?.Message) {
      ElMessage.error(error.response.data.Message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

function handleAvatarError(e, row) {
  // 设置为默认头像
  e.target.src = defaultAvatarUrl
  // 重新拉取用户数据
  fetchUsers()
}

onMounted(() => {
  // 检查是否需要强制刷新
  if (localStorage.getItem('forceUserRefresh') === 'true') {
    fetchUsers()
    localStorage.removeItem('forceUserRefresh')
  } else {
    fetchUsers()
  }
})
</script>

<style scoped>
.user-management {
  background: #f5f7fa;
  min-height: calc(100vh - 52px);
  padding: 0 0 60px 0;
}

.user-card {
  background: transparent;
  border-radius: 18px;
  box-shadow: none;
  padding: 8px 24px 24px 24px;
  max-width: 100%;
  margin: 0 auto;
  height: calc(100vh - 172px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.pretty-table {
  background: transparent !important;
  border-radius: 14px;
  font-size: 16px;
  width: 100%;
  flex: 1;
  overflow: hidden;
}

.pretty-table th {
  background: #f5f7fa !important;
  color: #3a4664;
  font-weight: 700;
  border-bottom: 1.5px solid #e6e8eb !important;
  letter-spacing: 0.5px;
  font-size: 15px;
  padding: 14px 12px !important;
  text-align: left !important;
}

.pretty-table td {
  background: #fff !important;
  border-bottom: 1.5px solid #f0f0f0 !important;
  color: #2d3a4a;
  font-size: 15px;
  text-align: left !important;
}

.pretty-table .el-table__row:hover > td {
  background: #f0f6ff !important;
}

.el-button {
  border-radius: 4px !important;
  font-weight: 500;
  min-width: 80px;
  font-size: 14px;
  padding: 14px 20px;
  margin-right: 0;
  margin-bottom: 0;
  transition: all 0.2s;
}

.el-button:last-child {
  margin-right: 0;
}

.el-button--danger {
  background: #f56c6c !important;
  color: #ffffff !important;
  border: none !important;
}

.el-button--danger:hover {
  background: #f78989 !important;
  color: #ffffff !important;
}

.el-button--success {
  background: #67c23a !important;
  color: #ffffff !important;
  border: none !important;
}

.el-button--success:hover {
  background: #85ce61 !important;
  color: #ffffff !important;
}

.el-button--primary {
  background: #409eff !important;
  color: #ffffff !important;
  border: none !important;
}

.el-button--primary:hover {
  background: #66b1ff !important;
  color: #ffffff !important;
}

.el-button--default {
  background: #ffffff !important;
  color: #606266 !important;
  border: 1px solid #dcdfe6 !important;
}

.el-button--default:hover {
  background: #f5f7fa !important;
  color: #409eff !important;
  border-color: #c6e2ff !important;
}

.pretty-tag {
  background: #f0f9ff !important;
  color: #0369a1 !important;
  border: 1px solid #bae6fd !important;
  border-radius: 6px !important;
  padding: 4px 10px !important;
  font-weight: 400;
  font-size: 12px;
  margin-right: 6px;
  margin-bottom: 4px;
  box-shadow: none;
  display: inline-block;
  max-width: none;
  white-space: normal;
  overflow: visible;
  text-overflow: unset;
  letter-spacing: 0.3px;
}

.role-tags-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  white-space: normal;
  max-width: 100%;
  gap: 0 0;
  margin-top: 2px;
  margin-bottom: 2px;
}

.permission-tags-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  white-space: normal;
  max-width: 100%;
  gap: 0 0;
  margin-top: 2px;
  margin-bottom: 2px;
}

.create-user-btn {
  background: #409eff !important;
  color: #ffffff !important;
  border: none !important;
  border-radius: 4px !important;
  font-weight: 500;
  font-size: 14px;
  padding: 8px 16px !important;
  box-shadow: none;
  transition: all 0.2s;
  margin-bottom: 0;
}

.create-user-btn:hover {
  background: #337ecc !important;
  color: #ffffff !important;
}

.user-actions-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

/* 角色分配对话框样式 */
.role-checkbox-item {
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.2s ease;
}

.role-checkbox-item:hover {
  background-color: #f5f7fa;
}

.role-checkbox-item .el-checkbox {
  width: 100%;
  margin-right: 0;
}

.role-checkbox-item .el-checkbox__label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  line-height: 1.4;
}

.role-name {
  font-weight: 500;
  color: #303133;
}

.role-scope {
  color: #909399;
  font-size: 12px;
}

/* 优化复选框动画 */
:deep(.el-checkbox__input) {
  transition: all 0.15s ease;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
  transform: scale(1.02);
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
  font-weight: 500;
}

/* 优化滚动性能 */
:deep(.el-checkbox-group) {
  will-change: transform;
}

/* 减少重绘和重排 */
.role-checkbox-item {
  will-change: auto;
  contain: layout style;
}

/* 对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

.animate-in {
  animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.role-tag {
  background: #fff !important;
  color: #e5739a !important;
  border: 1px solid #e5739a !important;
  border-radius: 8px !important;
  font-weight: bold;
  font-size: 13px;
  padding: 4px 16px !important;
  margin-right: 6px;
  margin-bottom: 4px;
  box-shadow: 0 2px 8px rgba(229,115,154,0.06);
  letter-spacing: 1px;
  display: inline-block;
  transition: none;
}
</style>